<?php

namespace App\Http\Requests;

use App\Models\Role;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use App\Models\Topic;

class TopicRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $type = $this->request->get('type');
        $user = $this->user();
        if ($type == Topic::TYPE_RECRUITMENT)
        {
            //招聘，只有商家能发
            $adminUser = $user->adminUser;
            if ($adminUser && $adminUser->isRole(Role::SLUG_AGENTL))
            {
                return true;
            }
        }
        else
        {
            //趣事、求职，都能发
            return true;
        }
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'type' => ['required', Rule::in(array_keys(Topic::$typeNames))],
            'content' => ['required'],
            'images' => ['array']
        ];
    }

    public function validator()
    {
        $v = \Validator::make($this->request->all(), [
            'type' => ['required', Rule::in(array_keys(Topic::$typeNames))],
            'content' => ['required'],
            'images' => ['array']
        ]);
        $applyJobFields = ['apply_job.intention', 'apply_job.province_code', 'apply_job.city_code', 'apply_job.district_code', 'apply_job.phone'];
        $v->sometimes($applyJobFields, "required", function ($input) {
            return $input->type == Topic::TYPE_APPLY_JOB;
        });

        return $v;
    }
}
